/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-07-04 01:36:52
 * @LastEditors: cxguo
 * @LastEditTime: 2020-09-15 11:15:34
 */
import {
	login,
	logout,
	register,
	getUserInfo
} from '@/apis/sys/users'
import {
	initApp
} from '@/apis/sys/system.js'

import {
	getToken,
	setToken,
	removeToken
} from '@/common/auth.js'

const state = {
	token: getToken(),
	userInfo: null,
	appData: null
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USER_INFO: (state, data) => {
		state.userInfo = data
	},
	SET_APP_INFO: (state, data) => {
		state.appData = data
	},
	SET_BUS_SETUP: (state, data) => {
		Object.keys(data).forEach(key => {
			state.appData.businessSetup[key] = data[key]
		})
	}
}

const actions = {
	// user login
	login({
		commit
	}, params) {
		return new Promise((resolve, reject) => {
			login(params).then(res => {
				const access_token = res.data.access_token
				const token = access_token
				commit('SET_TOKEN', token)
				setToken(token)
				resolve(res)
			}).catch(error => {
				reject(error)
			})
		})
	},

	/**
	 * 租户注册
	 * @param {*} param0
	 * @param {*} userInfo
	 */
	register({
		commit
	}, params) {
		return new Promise((resolve, reject) => {
			register(params).then(res => {
				if (!res.data.flag) return reject(new Error(res.data.message))
				const token = res.data.data
				commit('SET_TOKEN', token)
				setToken(token)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// get user info
	getInfo({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			getUserInfo().then(res => {
				const data = res.data.data
				if (!data) {
					reject('Verification failed, please Login again.')
				}
				commit('SET_USER_INFO', data)
				resolve(data)
			}).catch(error => {
				reject(error)
			})
		})
	},

	initApp({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			initApp().then(res => {
				if (!res.data.flag) {
					reject(new Error('初始化应用失败！'))
					return
				}
				const data = res.data.data
				commit('SET_APP_INFO', data)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({
		commit,
		state,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			// 清除token
			commit('SET_TOKEN', null)
			// 清除appData
			commit('SET_APP_INFO', null)
			removeToken()
			resolve()
		})
	},

	// remove token
	resetToken({
		commit
	}) {
		return new Promise(resolve => {
			commit('SET_TOKEN', null)
			removeToken()
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}